#include "settings.hpp"

using namespace Gtk;
using namespace Glib;
using namespace sigc;
using namespace std;
using namespace Gnome;

using namespace boost::filesystem;

SettingsManagerClass SettingsManager;

AppSettings SettingsManagerClass::GetSettings(){
	return settings;
}

void SettingsManagerClass::SetSettings(AppSettings newsettings){
	settings=newsettings;
}

bool SettingsManagerClass::LoadSettings(){
    if(exists(SettingsFile)){
        TiXmlDocument xml(SettingsFile.c_str());
        xml.LoadFile();
        DEBUG(dump_to_stdout(SettingsFile.c_str()));
        const TiXmlElement *root=xml.RootElement();
        DEBUG(cout<<"Root element: "<<root<<endl);
        settings.Url=XMLGetChildByName(*root,"url")->GetText();
        settings.Path=XMLGetChildByName(*root,"path")->GetText();
        settings.User=XMLGetChildByName(*root,"user")->GetText();
        settings.Pass=XMLGetChildByName(*root,"pass")->GetText();
        settings.EncKey=XMLGetChildByName(*root,"enckey")->GetText();
        return true;
    }
    return false;
}

bool SettingsManagerClass::CheckSettings(string filename){
	return exists(SettingsFile) && LoadSettings();
}

void SettingsManagerClass::SaveSettings(){
    AutoFreeList afl;
    TiXmlDocument xml;
    TiXmlElement* root=afl.AddDel(new TiXmlElement("settings"));
    xml.LinkEndChild(root);
    
    TiXmlElement* url=afl.AddDel(new TiXmlElement("url"));
    url->LinkEndChild(afl.AddDel(new TiXmlText(settings.Url)));
    TiXmlElement* path=afl.AddDel(new TiXmlElement("path"));
    path->LinkEndChild(afl.AddDel(new TiXmlText(settings.Path)));
    TiXmlElement* user=afl.AddDel(new TiXmlElement("user"));
    user->LinkEndChild(afl.AddDel(new TiXmlText(settings.User)));
    TiXmlElement* pass=afl.AddDel(new TiXmlElement("pass"));
    pass->LinkEndChild(afl.AddDel(new TiXmlText(settings.Pass)));
    TiXmlElement* enckey=afl.AddDel(new TiXmlElement("enckey"));
    enckey->LinkEndChild(afl.AddDel(new TiXmlText(settings.EncKey)));
    
    root->LinkEndChild(url);
    root->LinkEndChild(path);
    root->LinkEndChild(user);
    root->LinkEndChild(pass);
    root->LinkEndChild(enckey);
    
    xml.SaveFile(SettingsFile);
}

const TiXmlElement *XMLGetChildByName(const TiXmlNode &node, const string name){
    for(const TiXmlElement *child=node.FirstChildElement();child;child=child->NextSiblingElement()){
        if(child->Value()==name)return child;
    }
    return NULL;
}
